package com.example.xxpk.service.userprops;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.xxpk.bo.UserPropsInfo;
import com.example.xxpk.mapper.UserPropsMapper;
import com.example.xxpk.pojo.UserProps;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhangguihong
 * @since 2025-02-13
 */
@Service
@RequiredArgsConstructor
public class UserPropsServiceImpl extends ServiceImpl<UserPropsMapper, UserProps> implements IUserPropsService {


    private final  UserPropsMapper userPropsMapper;

    @Override
    public List<UserPropsInfo> getUserPropsInfoByUserId(Integer userId) {
        return userPropsMapper.getUserPropsInfoByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean obtainProps(Integer userId, Integer propsId, Integer propsCount) {
        // 根据用户 ID 和道具 ID 查询是否存在记录
        QueryWrapper<UserProps> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("props_id", propsId);
        UserProps existingUserProps = userPropsMapper.selectOne(queryWrapper);
        if (existingUserProps != null) {
            // 记录存在，更新道具数量和最新获得时间
            existingUserProps.setPropsCount(existingUserProps.getPropsCount() + propsCount);
            existingUserProps.setNewTime(LocalDateTime.now());
            return userPropsMapper.updateById(existingUserProps) > 0;
        } else {
            // 记录不存在，新增一条记录
            UserProps newUserProps = new UserProps();
            newUserProps.setUserId(userId);
            newUserProps.setPropsId(propsId);
            newUserProps.setCurrentLv(1);
            newUserProps.setPropsCount(propsCount);
            newUserProps.setNewTime(LocalDateTime.now());
            newUserProps.setCreateTime(LocalDateTime.now());
            return userPropsMapper.insert(newUserProps) > 0;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean useProps(Integer userId, Integer propsId, Integer useCount) {
        // 根据用户 ID 和道具 ID 查询用户的道具记录
        QueryWrapper<UserProps> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).eq("props_id", propsId);
        UserProps userProps = this.getOne(queryWrapper);

        if (userProps == null) {
            // 用户没有该道具，使用失败
            return false;
        }

        if (userProps.getPropsCount() < useCount) {
            // 用户拥有的道具数量不足，使用失败
            return false;
        }

        // 更新道具数量
        userProps.setPropsCount(userProps.getPropsCount() - useCount);
        userProps.setNewTime(LocalDateTime.now());

        // 保存更新后的记录
        return this.updateById(userProps);
    }


}
